package com.java.androidmarket.controller;

import com.alibaba.fastjson.JSON;
import com.java.androidmarket.aspect.CheckUser;
import com.java.androidmarket.dto.UserDTO;
import com.java.androidmarket.entity.*;
import com.java.androidmarket.service.*;
import com.java.androidmarket.utils.JWTUtils;
import com.java.androidmarket.utils.RedisUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import jodd.util.StringUtil;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * description:
 * author:张腾
 * date:2021-04-25
 */

@RestController
@CrossOrigin
@RequestMapping("user")
@Api(tags = "用户模块")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private RedissonClient redissonClient;

    private static String ip = "http://192.168.205.54:8989/";

    //http://192.168.205.54:8989/
    //eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2MjMwNDQxNTQsInVzZXJJZCI6IjUifQ.9OArwq0r5wm2FnhITpQFNuzDpJLNMRJrWWZcabFbjbA


    @PostMapping("login")
    @ApiOperation(value = "用户登录", notes = "用户登录接口")
    @ApiImplicitParam(dataType = "User", name = "user", value = "用户实体类User")
    public Result login(@RequestBody User user){
       Map<String,Object> map = new HashMap<>();

       System.out.println("数据库用户登录");
       String userDB = userService.login(user.getUserName(), user.getUserPwd());
       if (userDB.equals("密码错误！") || userDB.equals("该账号不存在！")) {
           return Result.error(userDB);
       }else {
           //数据库中用户信息
           User userDB1 = JSON.parseObject(userDB,User.class);

           //生成token
           HashMap<String, String> payLoad = new HashMap<>();
           payLoad.put("userId",String.valueOf(userDB1.getUserId()));
           String token = JWTUtils.getToken(payLoad);

           if (!redisUtils.exists("Token"+userDB1.getUserId())){
               redisUtils.set("Token"+userDB1.getUserId(),token);
           }else{
               //每次每个用户登录往redis存token，确保每个用户只能在一台机器登录
               String redisToken = (String) redisUtils.get("Token" + userDB1.getUserId());
               if (!redisToken.equals(token)){
                   redisUtils.set("Token"+userDB1.getUserId(),token,2L, TimeUnit.DAYS);
               }
           }
           //返回前端数据
           UserDTO reUser = new UserDTO();
           reUser.setId(userDB1.getUserId()).setUserName(userDB1.getUserName()).setImg(ip+userDB1.getUserImg())
                    .setToken(token);

           String key = "User:"+userDB1.getUserId();
           redisUtils.hmSet(key,"UserName",userDB1.getUserName());
           redisUtils.hmSet(key,"UserId",String.valueOf(userDB1.getUserId()));
           redisUtils.hmSet(key,"UserPwd",userDB1.getUserPwd());
           redisUtils.hmSet(key,"UserImg",ip+userDB1.getUserImg());

           return Result.success(reUser);
       }

    }


    @PostMapping ("getUser")
    @ApiOperation(value = "获取用户信息", notes = "根据token获取用户信息")
    public Result getUserByID(HttpServletRequest request){
        String token = request.getHeader("Token");

        UserDTO user = new UserDTO();

        String userId = JWTUtils.DecodedGetID(token);
        String key = "User:"+userId;
        if (redisUtils.exists(key)) {
            System.out.println("redis获取用户信息");
            String userImg = (String) redisUtils.hmGet(key,"UserImg");
            String userName = (String) redisUtils.hmGet(key, "UserName");

            user.setId(Integer.valueOf(userId)).setUserName(userName).setImg(userImg);
        }else {
            //修改用户个人信息后会走
            System.out.println("数据库获取用户信息");
            User userDB = userService.getUser(Integer.valueOf(userId));
            user.setImg(ip + userDB.getUserImg()).setUserName(userDB.getUserName()).setId(Integer.parseInt(userId));
            redisUtils.hmSet(key, "UserId", userId);
            redisUtils.hmSet(key, "UserName", userDB.getUserName());
            redisUtils.hmSet(key, "UserImg", user.getImg());
            redisUtils.hmSet(key, "UserPwd", userDB.getUserPwd());

        }
        return Result.success(user);

    }


    @PostMapping(value = "uploadHead" )
    public Result uploadHead(MultipartFile upLoadfile, HttpServletRequest request) throws IOException {
//        MultipartFile upLoadfile = uploadDTO.getUpLoadfile();
//        HttpServletRequest request = uploadDTO.getRequest();
        String header = request.getHeader("Content-Type");
        System.out.println(header);

        String fileName = "";
        String originalFilename = upLoadfile.getOriginalFilename();
        String extendName = StringUtil.toLowerCase(originalFilename.substring(originalFilename.lastIndexOf(".") + 1, originalFilename.length()));

        String uuid = UUID.randomUUID().toString().replace("-", "").toUpperCase();
        fileName = uuid +"_"+ originalFilename.substring(0,originalFilename.lastIndexOf(".")+1)+extendName ;

        String realPath = ClassUtils.getDefaultClassLoader().getResource("static").getPath();
        System.out.println(realPath);

        File file = new File(realPath);
        if (!file.exists()){
            file.mkdir();
        }
        //生成文件
        File f = new File(file,fileName);
        //上传！！
        upLoadfile.transferTo(f);

        String token = request.getHeader("Token");
        int userId = Integer.parseInt(JWTUtils.DecodedGetID(token));
        userService.uploadHead(fileName,userId);
        redisUtils.del("User:"+userId);


        return Result.success();
    }


    @PostMapping("register")
    @ApiOperation(value = "用户注册", notes = "根据用户名和密码注册用户")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "String", name = "userName", value = "用户名"),
            @ApiImplicitParam(dataType = "String", name = "userPwd", value = "用户密码")
    })
    public Result register(@RequestBody User user){

        String re = userService.register(user.getUserName(), user.getUserPwd());

        if (re.equals("用户名已存在")){
            return Result.error(re);
        }else {
            User userDB = JSON.parseObject(re, User.class);

            //生成token
            HashMap<String, String> payLoad = new HashMap<>();
            payLoad.put("userId",String.valueOf(userDB.getUserId()));
            String token = JWTUtils.getToken(payLoad);


            //每次每个用户登录往redis存token，确保每个用户只能在一台机器登录
            redisUtils.set("Token"+userDB.getUserId(),token,2L,TimeUnit.DAYS);

            //返回前端数据
            UserDTO reUser = new UserDTO();
            reUser.setId(userDB.getUserId()).setUserName(userDB.getUserName()).setImg(ip+userDB.getUserImg())
                    .setToken(token);

            String key = "User:"+userDB.getUserId();
            redisUtils.hmSet(key,"UserName",userDB.getUserName());
            redisUtils.hmSet(key,"UserId",String.valueOf(userDB.getUserId()));
            redisUtils.hmSet(key,"UserPwd",userDB.getUserPwd());
            redisUtils.hmSet(key,"UserImg",ip+userDB.getUserImg());

            return Result.success(reUser);
        }

    }


    @PostMapping("check")
    @ApiOperation(value = "查重用户名" ,notes = "根据用户名查找是否该用户名已存在")
    @ApiImplicitParam(dataType = "String", name = "userName", value = "用户名")
    public Result checkName(@RequestBody User user){

        if (userService.checkName(user.getUserName())) {
            return Result.success("用户名已存在");
        }else{
            return Result.success();
        }
    }

    @PostMapping("update")
    @ApiOperation(value = "更新信息", notes = "修改用户个人信息")
    @ApiImplicitParam(dataType = "User", name = "user", value = "用户实体类User")
    public Result updateUser(@RequestBody User user){

        if (redisUtils.exists("User:"+user.getUserId())) {
            redisUtils.del("User:"+user.getUserId());
        }
        System.out.println("修改用户信息");
        if (userService.updateUser(user)) {
            return Result.success();
        }else {
            return Result.success("用户名已存在");
        }

    }

    @GetMapping("getBrowseList")
    @ApiOperation(value = "获取用户浏览记录", notes = "获取用户最近浏览30条商品记录")
    @ApiImplicitParam(dataType = "int", name = "userId", value = "用户ID")
    @CheckUser
    public Result getBrowseList(int userId){
        System.out.println("获取用户浏览记录");
        Set<Goods> browseList = redisUtils.zGet("Recent_browse_list:" + userId);
//        browseList.forEach(value-> System.out.println(value));

        return Result.success(browseList, browseList.size());
    }

    @PostMapping("delBrowseList")
    @ApiOperation(value = "删除用户浏览记录", notes = "清空用户浏览记录")
    @ApiImplicitParam(dataType = "int", name = "userId", value = "用户ID")
    public Result delBrowseList(@RequestBody User user){
        System.out.println("删除用户浏览记录");
        if (redisUtils.exists("Recent_browse_list:" + user.getUserId())) {
            redisUtils.del("Recent_browse_list:" + user.getUserId());
        }

        return Result.success();
    }

    @PostMapping("logout")
    public Result logout(@RequestBody User user){
        redisUtils.del("Token"+user.getUserId());
        return Result.success();
    }

    @PostMapping("{path}/test")
    public void update(@PathVariable("path") String path,@RequestBody User user) {
        System.out.println(path);
        System.out.println(user);
    }
}
